package controllers

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"go_backend/models"
	"gopkg.in/olivere/elastic.v6" //这里使用的是版本5，最新的是6，有改动
	"time"
)

var (
	client *elastic.Client
	host   = "http://101.132.156.118:9200/"
	ctx    = context.Background()
)

//type buckets &struct {
//	Buckets []*struct {
//		chapter_id int 'json:"key"'
//		total_user struct {
//			value int 'json:"value"'
//		} 'json:"total_user"'
//		book_id struct {
//			book_id int 'json:"book_id"'
//		} 'json:"book_info.hits.hits.Source"'
//	}
//}

type ChapterController struct {
	beego.Controller
}

//type Book struct {
//	chapter_id int64
//	visit_num int64
//	book_id int64
//}

func init() {
	var err error
	client, err = elastic.NewClient(elastic.SetSniff(false), elastic.SetURL(host))
	if err != nil {
		panic(err)
	}
}

func (c *ChapterController) AnalysisChapter() {
	// 取聚合中的book_id
	fsc := elastic.NewFetchSourceContext(true).Include("book_id")
	bkagg := elastic.NewTopHitsAggregation().FetchSourceContext(fsc).Size(1)
	// distinct user_id
	caagg := elastic.NewCardinalityAggregation().Field("user_id")
	// groupby chapter_id
	agg := elastic.NewTermsAggregation().Field("chapter_id").
		SubAggregation("total_user", caagg).SubAggregation("book_info", bkagg)

	yesDay := time.Now().AddDate(0,0,-1).Format("2006-01-02")
	start_time := yesDay + " 00:00:00"
	end_time := yesDay + " 23:59:59"
	//fmt.Print(yesDay,start_time,end_time)

	start_time = "2018-07-31 16:40:00"
	end_time = "2018-07-31 16:41:59"

	// 格式化时间搜索
	temq := elastic.NewRangeQuery("created_at").
		Gte(start_time).
		Lte(end_time).
		Format("yyyy-MM-dd HH:mm:ss")

	res, err := client.Search("book").
		Type("subscribe").
		Query(temq).
		Size(0).
		Aggregation("total_chapter", agg).
		Do(ctx)

	if err != nil {
		println(err.Error())
	}
	//同步es数据到结构体
	buckets := &struct {
		Buckets []*struct {
			ChapterId int64 `json:"key"`
			DocCount int64 `json:"doc_count"`
			TotalUser struct {
				Value int64 `json:"value"`
			} `json:"total_user"`
			BookInfo struct {
				Hits struct{
					Hits []struct{
						SourceData struct{
							BookId int64 `json:"book_id"`
						} `json:"_source"`
					} `json:"hits"`
				} `json:"hits"`
			} `json:"book_info"`
		}`json:"buckets"`
	}{}
	bs, _ := res.Aggregations["total_chapter"].MarshalJSON()
	err = json.Unmarshal(bs, buckets)
	if err != nil {
		fmt.Println(err)
		return
	}
	//数据保存到切片
	items := make([]*models.Book, len(buckets.Buckets))
	for i, v := range buckets.Buckets {
		items[i] =  &models.Book{
			ChapterId: v.ChapterId,
			VisitNum: v.TotalUser.Value,
			BookId: v.BookInfo.Hits.Hits[0].SourceData.BookId,
		}
	}
	println(items)

	//同步数据到mysql
	platform := 1 //十音
	models.AnalysisChapterData(platform, items)


}
